<?php

namespace app\common\controller;

use app\api\model\Member;
use app\exceptions\ApiException;
use think\App;
use think\facade\Config;
use think\facade\Request;
use Throwable;
use think\facade\Event;
use app\common\library\Auth;
use think\exception\HttpResponseException;
use app\common\library\token\TokenExpirationException;

class Frontend extends Api
{
    /**
     * 无需登录的方法
     * 访问本控制器的此方法，无需会员登录
     * @var array
     */
    protected array $noNeedLogin = [];

    /**
     * 无需鉴权的方法
     * @var array
     */
    protected array $noNeedPermission = [];


    protected $request_array = [];

    /**
     * 权限类实例
     * @var Auth
     */
    protected Auth $auth;


    /**
     * 构造方法
     * @access public
     *
     * @param Request $request Request 对象
     */
    public function __construct(App $app)
    {
        $this->request = is_null($app->request) ? \think\facade\Request::instance() : $app->request;
        $this->request_array = $app->request->param();
        // 控制器初始化
        $this->_initialize();
    }


    /**
     * 初始化
     * @throws Throwable
     * @throws HttpResponseException
     */
    protected function _initialize()
    {
        $this->request_array = $this->request->param();
        $this->request->filter('trim,strip_tags,htmlspecialchars');
        // 检测是否需要验证登录
        if (!$this->match($this->noNeedLogin)) {
            $authorization = request()->header('authorization');
            //校验登录状态
            $token = trim(str_ireplace('Bearer', '', $authorization));
            if (!$token) {
                throw  new ApiException('未登录,请前往个人中心登录', 401);
            }
            $check_result = (new \app\common\model\Token())->check_token($token, $act_type = 1);
            if ($check_result['status'] == '2') {
                throw  new ApiException($check_result['message'], 401);
            }
            $this->request_array['member_id'] = $check_result['member_id'];
            //查询状态
            $user = (new Member())->where(['id' => $check_result['member_id']])->find();
            if (empty($user)) {
                throw  new ApiException('用户不存在', 401);
            }
            if ($user && $user['status'] == 0) {
                throw  new ApiException('您的账号已被冻结', 401);
            }
        }
    }

    public function match($arr = [])
    {
        $request = Request::instance();
        $arr = is_array($arr) ? $arr : explode(',', $arr);
        if (!$arr) {
            return false;
        }
        $arr = array_map('strtolower', $arr);
        // 是否存在
        if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
            return true;
        }

        // 没找到匹配
        return false;
    }
}